<template>
  <el-card class="sales content-card" v-loading="loading">
    <el-row :gutter="24">
      <el-col :md="24" :sm="24" style="margin-bottom: 12px">
        <div class="card-header-extra">
          <div class="card-header-extra-options hidden-xs-only">
<!--            <el-link :underline="false" :class="{checked: cycle == 'day30'}" @click="handleSelectCycle('day30')">今日</el-link>-->
<!--            <el-link :underline="false" :class="{checked: cycle == 'week'}" @click="handleSelectCycle('week')">本周</el-link>-->
<!--            <el-link style="margin-right: 10px" :underline="false" :class="{checked: cycle == 'month'}" @click="handleSelectCycle('month')">本月</el-link>-->
            <el-date-picker
              v-model="value1"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="default"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="onchange"
            />
            <div class="sales_title">时间范围内总交易额：100W 退款金额：50W 实际交易金额：50W</div>
          </div>

        </div>
        <div class="sales-chart-warp">
          <VChart :loading="loading" :option="option" autoresize/>
        </div>
      </el-col>


    </el-row>
  </el-card>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue';
import VChart from 'vue-echarts';
import useLoading from '@/hooks/use-loading';
import { consoleShopOrder, consoleStoreOrder, ShopSalesData } from '@/api/dashboard';
import numeral from 'numeral';
import { IconCircle, SvgIcon } from '@/components/icon';

const [loading, setLoading] = useLoading(true);
const value1 = ref('')
const props = defineProps({
  type: {
    type: Number,
    default: 10
  }
}); // 增加 10% 的缓冲，如果没有有效值则设置为100
const maxAmount=ref()
const maxCount=ref()
const option = computed(() => {
  return {
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    legend: {
      data: ['交易额']
    },
    xAxis: {
      type: 'category',
      data: xAxisData.value,
      axisLine: {
        show: false,
      },
      axisTick: {
        show: true,
        alignWithLabel: true,
      },
    },
    yAxis: [
      {
        type: 'value',
        name: '',
        min: 0,
        // max: maxAmount.value, // 使用计算得到的最大值
        // axisLabel: {
        //   formatter: function(value) {
        //     return (value / 10000).toFixed(2) + ' w'; // 将值除以10000并添加单位
        //   }
        // },
      }
    ],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    series: [
      {
        name: '交易额',
        type: 'bar',
        data: amounts.value,
        barWidth: '20%',
        itemStyle: {
          color: '#2085FF',  // 设置折线颜色为红色
        },
      },
    ],
  };
});

const cycle = ref('week');
const handleSelectCycle = (item: string) => {
  // 清空 value1
  value1.value = [];
  cycle.value = item;
  const today = new Date();
  if (item === 'day30') {
    // 获取今日的日期
    const dateString = today.toISOString().split('T')[0]; // 格式化为 YYYY-MM-DD
    const dateString1 = today.toISOString().split('T')[0];
    value1.value.push(dateString,dateString1);
  } else if (item === 'week') {
    // 获取本周从周一到周日的日期
    const today = new Date(); // 获取当前日期
// 获取今天是周几（0=周日，1=周一，...，6=周六）
    const dayOfWeek = today.getDay();
// 计算本周的周一和周日
    const monday = new Date(today); // 创建今天的日期副本
    monday.setDate(today.getDate() - (dayOfWeek === 0 ? 6 : dayOfWeek - 1)); // 计算本周的周一
    const sunday = new Date(monday); // 创建周一的日期副本
    sunday.setDate(monday.getDate() + 6); // 计算本周的周日
    value1.value.push(monday.toISOString().split('T')[0]);
    value1.value.push(sunday.toISOString().split('T')[0]);
  } else if (item === 'month') {
    // 获取本月的日期范围
    const now = new Date(); // 获取当前日期时间
    const monthStart = new Date(now.getFullYear(), now.getMonth(), 1,23, 59, 59); // 获取本月第一天的日期时间
    const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0,23, 59, 59); // 获取本月最后一天的日期时间（时间为23:59:59）
    value1.value.push(monthStart.toISOString().split('T')[0]);
    value1.value.push(monthEnd.toISOString().split('T')[0]);
  }
  fetchDataList();
};
const legendData = ref<string[]>([]);
const xAxisData = ref<string[]>([]);
const yAxisData = ref<any[]>([{type: 'value'}]);
const seriesData = ref<any[]>([]);
const salesData = ref<ShopSalesData[]>([]);
const amounts=ref()
const fees=ref()
const onchange=()=>{
  fetchDataList()
}

const fetchDataList = async () => {
  setLoading(true);
  try {
    // if (props.type == 1) {
    let params={
      type:props.type,
      action:'list',
      start_date:value1.value[0],
      end_date:value1.value[1]
    }
    const { body } = await consoleShopOrder(params);
    const dates = body.map(item => item.date);
    amounts.value = body.map(item => parseFloat(item.amount)); // 转换为数字
    fees.value = body.map(item => parseFloat(item.fee)); // 转换为数字

    // 计算最大值并增加缓冲
    maxAmount.value = Number((Math.max(...amounts.value) * 1.1).toFixed(2));
    maxCount.value = Number((Math.max(...fees.value) * 1.5).toFixed(0));

    xAxisData.value = dates || [];
  } catch (err) {
  } finally {
    setLoading(false);
  }
};
handleSelectCycle('month')
// fetchDataList();

defineExpose({fetchDataList});
</script>

<style lang="scss" scoped>
.sales {
  .sales-item-label {
    margin: 0 0 10px 0;
  }

  .sales-chart-warp {
    height: 480px;
    width: 100%;
  }
.sales_title{
  background: rgba(250,140,20,0.1);
  border-radius: 2px;
  border: 1px solid #FA8C14;
  padding: 5px 15px;
  margin-top: 8px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #FA8C14;
}
  .ranking {
    list-style-type: none;
    padding: 0;
    margin: 0;

    li {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 14px;

      .circle {
        width: 24px;
        height: 24px;
        line-height: 24px;
        text-align: center;
        font-size: 12px;
        margin-right: 8px;

        &.active {
          background-color: var(--el-color-primary-light-9);
        }
      }
    }
  }

  .card-header-extra {
    width: 100%;
    margin-right: 1rem;
    display: flex;
    align-content: center;
    margin-bottom: 20px;
    .card-header-extra-options{
      //width: 30%;
      //float: right;
      //text-align: right;
      margin-right: 10px;
      margin-top:7px;
    }
    .card-header-extra-options {
      > a {
        margin-left: 16px;
      }
    }

    .el-date-editor {
      width: 250px;
    }
  }

  .el-link {
    &.checked {
      color: var(--el-color-primary)
    }
  }
}
</style>
